/*
 * Client.cpp
 *
 *  Created on: Dec 4, 2010
 *      Author: lycdragon
 */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

#include "Client.h"

char revfilebuffer[MAXFILESIZE];
string eString;
Message fmsg;
typedef struct buffer{
 char buff[512];
} buffer;

int Client::saveFileFromServer(char fileName[]){

	int opfd;
	struct buffer aBuffer;
	int n;
	string query;
	query.assign(fileName);

	Message msg;
	msg.setMessageType(CL_2_LS_GET_CHUNK);
	msg.setMessage(query);

	int sockfd = asClient(name,lsipaddr, portofls);
	char buf[MAXDATASIZE];
	strcpy(buf,msg.encode().c_str());
	send(sockfd, buf, msg.encode().length(), 0);

	string localFileName="sharedFolder/"+query;
	fileName = strcpy(fileName, localFileName.c_str());
	opfd=open(fileName, O_RDWR | O_CREAT | O_EXCL, 0666);
	n=read(sockfd, aBuffer.buff, sizeof(aBuffer.buff));
	while(n > 0){
	 	write(opfd,aBuffer.buff,n);
	  	n=read(sockfd, aBuffer.buff, sizeof(aBuffer.buff));
	}
	close(opfd);
	return n;
}

Client::Client() {

	ifstream fin("CLconfig.ini");
	fin >> lsipaddr >> portofls >> sharefolder;
	cout << lsipaddr << " " << portofls <<" "<<sharefolder<<endl;
	this->name=string("Client");
	string query;

	while(1){
		cout << "Please input the file name you want to search:" << endl;
		cin >> query;
		this->sendRequest(query);
	}
}
	void Client::sendRequest(string query){
		char buf[MAXDATASIZE];
		int sockfd = asClient(name,lsipaddr, portofls);
		string fname(sharefolder);
		string response;
		fname += query;
/*		MessageLS2LS ls2ls(LS_2_LS_GET_CHUNK, msgString);
		// Get encoded string to send over network
		encodedString = ls2ls.encode();
		// Send encodedString over a network.
		// Once u receive at the destination, decode it.
		success = msg.decode(encodedString);*/
		char typ[2], ntyp[2];
		strcpy(typ, LC_FILE_CL);
		strcpy(ntyp, CLIENT_ST_NAME);

		Message msg(ntyp, query);
		string ntp = msg.encode();
		strcpy(buf, ntp.c_str());

		send(sockfd, buf, ntp.length(), 0);
		memset(buf, 0, sizeof(buf));
		recv(sockfd, buf, MAXDATASIZE, 0);

		response.assign(buf);
		Message fmsg;

		bool success = fmsg.decode(response);
		if (success) {
			if(fmsg.getMessageType()==MSG_CHUNK_INFO_ADV){
				MessageChunkInfo msg=MessageChunkInfo(MSG_CHUNK_INFO_ADV);
				msg.setChunksFromRawMsg(response);
				std::vector<string> chunks=msg.getChunks();
				if(chunks.size()==0){
					cout<<"Requested file is not found in the entire network !" <<endl ;
				}
				else{
					cout<< "Printing the chunk information"<<endl;
					for(vector<string>::iterator it = chunks.begin(); it != chunks.end(); ++it){
							string Chunk=*it;;
							cout<< "File: "<<Chunk<<endl;
							char file[100];
							strcpy(file,Chunk.c_str());
							saveFileFromServer(file);
					}
					cout << "Transfer finished!" << endl;
				}

			}
		}
		close(sockfd);

	}


